//
//  IndoorMapViewNew.m
//  WisdomMallAPP
//
//  Created by apple on 14-1-13.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "IndoorMapViewNew.h"

#import "IndoorMapPath.h"


#import "ItemRelation.h"

#import "Constant.h"
#import "NSFileHandle+readLine.h"
#import "SampleFileInfo.h"

#define IMAGE_SIZE      15.0f
#define LOAD_SYNCHRONOUSLY 0 // Synchronous load is less code, easier to write - but poor for large images

#define ALLOW_2X_STYLE_SCALING_OF_SVGS_AS_AN_EXAMPLE 1 // demonstrates using the "SVGKImage.scale" property to scale an SVG *before it generates output image data*

#define ALLOW_SVGKFASTIMAGEVIEW_TO_DO_HIT_TESTING 1 // only exists because people ignore the docs and try to do this when they clearly shouldn't. If you're foolish enough to do this, this code will show you how to do it CORRECTLY. Look how much code this requires! It's insane! Use SVGKLayeredImageView instead if you need hit-testing!

#define SHOW_DEBUG_INFO_ON_EACH_TAPPED_LAYER 1 // each time you tap and select a layer, that layer's info is displayed on-screen

@interface ImageLoadingOptions : NSObject
@property(nonatomic) BOOL requiresLayeredImageView;
@property(nonatomic) CGSize overrideImageSize;
@property(nonatomic) float overrideImageRenderScale;
@property(nonatomic,strong) SVGKSourceLocalFile* localFileSource;
- (id)initWithSource:(SVGKSource*) source;

@end

static NSString * const kTimeIntervalForLastReRenderOfSVGFromMemory = @"timeIntervalForLastReRenderOfSVGFromMemory";

@implementation ImageLoadingOptions
- (id)initWithSource:(SVGKSource*) source
{
    self = [super init];
    if (self) {
        if( [source isKindOfClass:[SVGKSourceLocalFile class]])
            self.localFileSource = (SVGKSourceLocalFile*) source;
        else
            ; // cannot auto-select loading options for anything except local files / bundle files
        
        self.overrideImageRenderScale = 1.0;
        self.overrideImageSize = CGSizeZero;
    }
    return self;
}
@end

@interface IndoorMapViewNew ()
@property (nonatomic, strong) NSDate* startParseTime, * endParseTime;
@property (nonatomic, strong) UITapGestureRecognizer* tapGestureRecognizer;
@property (nonatomic, strong) IBOutlet UIActivityIndicatorView *viewActivityIndicator;
@property (nonatomic, strong) IBOutlet UIView* subViewLoadingPopup;

@end



@implementation IndoorMapViewNew



@synthesize viewActivityIndicator;
#if V_1_COMPATIBILITY_COMPILE_CALAYEREXPORTER_CLASS
@synthesize layerExporter = _layerExporter;
#endif


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
//        UIImage *floorImage = [UIImage imageNamed:@"masp.png"];
//        self.contentView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
//        self.contentView.image = floorImage;
//        self.contentView.center = CGPointMake(frame.size.width * 0.5f, frame.size.height * 0.5f);
//        self.contentView.contentMode = UIViewContentModeScaleAspectFit;
//        self.contentView.userInteractionEnabled = YES;
        
//        [self loadSVGFrom:[SampleFileInfo sampleFileInfoWithFilename:@"masp.svg"].source];
        
        
         }
    return self;
}

//- (void)setMapImage:(UIImage *)image
//{
//    self.contentView.image = image;
//}



CALayer* lastTappedLayer;
CGFloat lastTappedLayerOriginalBorderWidth;
CGColorRef lastTappedLayerOriginalBorderColor;
CATextLayer *textLayerForLastTappedLayer;
-(void) deselectTappedLayer
{
    if( lastTappedLayer != nil )
    {
#if ALLOW_SVGKFASTIMAGEVIEW_TO_DO_HIT_TESTING
        if( [self.contentView isKindOfClass:[SVGKFastImageView class]])
        {
            [lastTappedLayer removeFromSuperlayer]; // nothing else needed
        }
        else
#endif
        {
            lastTappedLayer.borderWidth = lastTappedLayerOriginalBorderWidth;
            lastTappedLayer.borderColor = lastTappedLayerOriginalBorderColor;
        }
        
        [textLayerForLastTappedLayer removeFromSuperlayer];
        textLayerForLastTappedLayer = nil;
        
        lastTappedLayer = nil;
    }
}

-(NSString*) layerInfo:(CALayer*) l
{
    return [NSString stringWithFormat:@"%@:%@", [l class], NSStringFromCGRect(l.frame)];
}

#pragma mark === 刷新视图
- (void)clearSubviews{
    for (UIView * view in self.subviews) {
        if (![view isKindOfClass:[SVGKLayeredImageView class]]) {
            [view removeFromSuperview];
        }else{
            self.contentView.image = nil;
        }
    }
    
}

- (void)loadSVGFrom:(SVGKSource *) svgSource rangeString:(NSString *)rangeString
{
//    [self willLoadNewResource];
    [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]]; // makes the animation appear
    
    self.startParseTime = self.endParseTime = [NSDate date]; // reset them
    
    SVGKImage *document = nil;
    ImageLoadingOptions* loadingOptions = [[ImageLoadingOptions alloc] initWithSource:svgSource];
    
    /** Detect URL vs file */
    self.startParseTime = [NSDate date];
    if( [svgSource isKindOfClass:[SVGKSourceURL class]])
    {
        @try
        {
            /**
             This would work, but won't let us read any errors:
             
             document = [SVGKImage imageWithContentsOfURL:[NSURL URLWithString:name]];
             
             so, instead, we create an SVGKSource explicitly (as this demo app is taking
             user-input, and we have no idea how valid it is!)
             
             
             */
            document = [SVGKImage imageWithSource:svgSource];
            
            [self internalLoadedResource:svgSource withOptions:loadingOptions parserOutput:(document==nil)?nil:document.parseErrorsAndWarnings  createImageViewFromDocument:document];
        }
        @catch( NSException* e )
        {
            [[[UIAlertView alloc] initWithTitle:@"SVG load failed" message:[NSString stringWithFormat:@"Error = %@", e] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
            
            [self internalLoadedResource:svgSource withOptions:loadingOptions parserOutput:nil createImageViewFromDocument:nil];
        }
        
    }
    else if( [svgSource isKindOfClass:[SVGKSourceLocalFile class]])
    {
        
        /** This demo shows different images being used in different ways.
         Here we setup special conditions based on the filename etc:
         */
        
        [self preProcessImageFor2X:loadingOptions];
        [self preProcessImageForAt160x240:loadingOptions];
        [self preProcessImageCheckWorkaroundAppleBugInGradientImages:loadingOptions rangeString:rangeString];
        
        /** Detect the magic name(s) for the nil-demos */
        if( svgSource == nil )
        {
            /** This demonstrates / tests what happens if you create an SVGKLayeredImageView with a nil SVGKImage
             */
//            [self didLoadNewResourceCreatingImageView:[[SVGKLayeredImageView alloc] initWithCoder:nil]];
        }else {
            /**
             the actual loading of the SVG file
             */
            
            
#if LOAD_SYNCHRONOUSLY
            document = [SVGKImage imageNamed:[name stringByAppendingPathExtension:@"svg"]];
            [self internalLoadedResource:name withOptions:loadingOptions createImageViewFromDocument:document];
#else
            SVGKParser* parser = [SVGKImage imageWithSource:svgSource
                                               onCompletion:^(SVGKImage *loadedImage, SVGKParseResult* parseResult)
                                  {
//                                      [self.tickerLoadingApplesNSTimerSucks invalidate];
                                      dispatch_async(dispatch_get_main_queue(), ^{
                                          // must be on main queue since this affects the UIKit GUI!
                                          [self internalLoadedResource:svgSource withOptions:loadingOptions parserOutput:parseResult createImageViewFromDocument:loadedImage];
                                      });
                                  }];
//            self.tickerLoadingApplesNSTimerSucks = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(tickLoadingSVG:) userInfo:parser repeats:TRUE];
#endif
        }
    }
    else
    {
        [[[UIAlertView alloc] initWithTitle:@"SVG load failed" message:[NSString stringWithFormat:@"Unknown kind of source. Should be a recognized SVGKSource subclass. Was actually : %@", [svgSource class]] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        
        [self internalLoadedResource:nil withOptions:loadingOptions parserOutput:nil createImageViewFromDocument:nil];
    }
//    [self didLoadNewResourceCreatingImageView:[[SVGKLayeredImageView alloc] initWithCoder:nil]];

}

#pragma mark====添加视图
-(void) internalLoadedResource:(SVGKSource*) source withOptions:(ImageLoadingOptions*) loadingOptions parserOutput:(SVGKParseResult*) parseResult createImageViewFromDocument:(SVGKImage*) document
{
    self.endParseTime = [NSDate date];
    
    SVGKImageView* newContentView = nil;
    if( loadingOptions.overrideImageRenderScale != 1.0 )
        document.scale = loadingOptions.overrideImageRenderScale;
    
    if( document == nil )
    {
        if( parseResult == nil )
        {
            [[[UIAlertView alloc] initWithTitle:@"SVG parse failed" message:@"Total failure. See console log" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        }
        else
        {
            [[[UIAlertView alloc] initWithTitle:@"SVG parse failed" message:[NSString stringWithFormat:@"Summary: %@",parseResult] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        }
        newContentView = nil; // signals to the rest of this method: the load failed
    }
    else
    {
        if( document.parseErrorsAndWarnings.rootOfSVGTree != nil )
        {
            //NSLog(@"[%@] Freshly loaded document (name = %@) has size = %@", [self class], name, NSStringFromCGSize(document.size) );
            
            /** NB: the SVG Spec says that the "correct" way to upscale or downscale an SVG is by changing the
             SVG Viewport. SVGKit automagically does this for you if you ever set a value to image.scale */
            if( ! CGSizeEqualToSize( CGSizeZero, loadingOptions.overrideImageSize ) )
                document.size = loadingOptions.overrideImageSize; // preferred way to scale an SVG! (standards compliant!)
            
            if( loadingOptions.requiresLayeredImageView )
            {
                newContentView = [[SVGKLayeredImageView alloc] initWithSVGKImage:document];
            }
            else
            {
                newContentView = [[SVGKFastImageView alloc] initWithSVGKImage:document];
                
                NSLog(@"[%@] WARNING: workaround for Apple bugs: UIScrollView spams tiny changes to the transform to the content view; currently, we have NO WAY of efficiently measuring whether or not to re-draw the SVGKImageView. As a temporary solution, we are DISABLING the SVGKImageView's auto-redraw-at-higher-resolution code - in general, you do NOT want to do this", [self class]);
                
                ((SVGKFastImageView*)newContentView).disableAutoRedrawAtHighestResolution = TRUE;
            }
        }
        
        if( parseResult.errorsFatal.count > 0 )
        {
            [[[UIAlertView alloc] initWithTitle:@"SVG parse failed" message:[NSString stringWithFormat:@"%@",parseResult] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
            //			[[[[UIAlertView alloc] initWithTitle:@"SVG parse failed" message:[NSString stringWithFormat:@"%i fatal errors, %i warnings. First fatal = %@",[document.parseErrorsAndWarnings.errorsFatal count],[document.parseErrorsAndWarnings.errorsRecoverable count]+[document.parseErrorsAndWarnings.warnings count], ((NSError*)[document.parseErrorsAndWarnings.errorsFatal objectAtIndex:0]).localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease] show];
            newContentView = nil; // signals to the rest of this method: the load failed
            
        }
    }
    
    self.sourceOfCurrentDocument = source;
    
//    [self didLoadNewResourceCreatingImageView:newContentView];

    if( newContentView != nil )
    {
        

        self.contentView = newContentView;
        
        
        UIScrollView * scroView = (UIScrollView *)self.superview;
        CGFloat hScale = CGRectGetHeight(scroView.frame)*(1.0/CGRectGetHeight(self.contentView.frame));
        CGFloat wScale = CGRectGetWidth(scroView.frame)*(1.0/CGRectGetWidth(self.contentView.frame));
        CGFloat scale = (hScale<wScale)?(hScale):(wScale);

        
        [scroView setMinimumZoomScale:scale];
        [scroView setZoomScale:scale];
        
        self.frame = CGRectMake(0, 0, CGRectGetWidth(self.contentView.frame)*scale, CGRectGetHeight(scroView.frame));
        [self.contentView addObserver:self forKeyPath:kTimeIntervalForLastReRenderOfSVGFromMemory options:0 context:nil];


        pathView = [[IndoorMapPathView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.contentView.frame), CGRectGetHeight(self.contentView.frame))];
        [self addSubview:self.contentView];
        [self addSubview:pathView];

        
        NSMutableArray * facilityArray = [self fetchFacilityPoint:[NSString stringWithFormat:@"设施%@",_floor]];
        for (int j = 0;j<facilityArray.count;j++) {
            NSArray * array = facilityArray[j];
            for (int i = 0;i<array.count;i++) {
                    AStarItem * item = array[i];
                    UIImageView * view = [[UIImageView alloc]init];
                    view.alpha = 0.8;
                    view.frame =CGRectMake(0, 0, 40, 50);
                    view.layer.masksToBounds = YES;
                    view.layer.cornerRadius = 10*VerticalRatio();
                    view.center = CGPointMake(item.id_col,item.id_row-30);

                   view.image = [UIImage imageNamed:[NSString stringWithFormat:@"faciality%d",j+1]];
                    view.tag = 1000*(j+1)+i;
                view.hidden = YES;
                [self addSubview:view];
            }
        }
        
        
        NSArray * nameArray = @[@" 楼梯",@" 扶梯",@" 观光电梯",@" 升降电梯",@" 洗手间",@" 询问处",@" 进出口"];
        for (UIView * view in scroView.superview.subviews) {
            if (view.tag>=500&&view.tag<=500+nameArray.count) {
                [view removeFromSuperview];
            }
        }
        for (int i = 0; i<nameArray.count; i++) {
            UIButton * view = [UIButton buttonWithType:UIButtonTypeCustom];
            view.frame =CGRectMake(CGRectGetWidth(scroView.superview.frame)-85, 84+32*i, 80, 25);
            view.titleLabel.font = [UIFont systemFontOfSize:18*VerticalRatio()];
            [view setImage:[UIImage imageNamed:[NSString stringWithFormat:@"indoorMap%d",9+i]] forState:UIControlStateNormal];
           [view setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
            [view setTitle:nameArray[i] forState:UIControlStateNormal];
            view.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            view.tag = 500+i+1;
            [view addTarget:self action:@selector(pickUpFacility:) forControlEvents:UIControlEventTouchUpInside];
            [scroView.superview insertSubview:view atIndex:2];

            }
        
        // 创建渐变图层
        self.userImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        self.userImage.image = [UIImage imageNamed:@"begin"];
        self.userImage.alpha = 0.8;
        [self addSubview:self.userImage];
        
        self.endImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        self.endImage.image = [UIImage imageNamed:@"ending"];
        self.endImage.alpha = 0.8;
        [self addSubview:self.endImage];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"havaAddEndImage" object:nil];
        
        self.clearsContextBeforeDrawing = YES;
        
        pathArray = [[NSMutableArray alloc] init];
        sIndex = -1;
        _previousScale = 1;
        _animationFinished = YES;
        
        _offset_y = OFFSET_Y;
        
        //astar algorithm
        astar = [[AStar alloc] init];
    }
}

#pragma mark === 添加店铺名称
- (void)drawStoreNames:(NSArray *)array{
    
    for (UIView * view in self.subviews) {
        if (view.tag>=10000) {
            [view removeFromSuperview];
        }
    }
    for (int i = 0; i<array.count; i++){
        NSDictionary * dic= array[i];
        NSString * pointStr = [Common stringFromData:dic[@"mstoPosition"]];
        NSArray * xyArray = [pointStr componentsSeparatedByString:@","];
        CGFloat x = [[[Common stringFromData:xyArray[0]]substringFromIndex:1]floatValue];
        CGFloat y = [[[Common stringFromData:xyArray[1]]substringToIndex:[Common stringFromData:xyArray[1]].length-1]floatValue];
        CGPoint point =CGPointMake(x, y);
        
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:15];
        label.text = [Common stringFromData:dic[@"mstoName"]];
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = 10000+i;
        label.center = point;
        [self insertSubview:label belowSubview:self.userImage];
    }
    

}

#pragma mark ========== 筛选设施  ===== 可能没有设施
- (void)pickUpFacility:(UIButton *)sender{
    for (UIView * view in self.subviews) {
        if (view.tag>=1000&&view.tag<10000) {
            if (view.tag/1000==sender.tag-500) {
                view.hidden = NO;
                if (view.center.x<0&&view.center.y<0) {
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"havaNoFacilities" object:nil];
                    NSArray * array = @[@(sender.tag-500),sender.titleLabel.text];
                    [[NSUserDefaults standardUserDefaults]setObject:array forKey:@"havaNoFacilities"];
                }
                if (![view.layer animationForKey:@"keyAnimation"]) {
                    CAKeyframeAnimation * keyAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
                    NSValue * p1 = [NSValue valueWithCGPoint:CGPointMake(view.center.x, view.center.y)];
                    NSValue * p2 = [NSValue valueWithCGPoint:CGPointMake(view.center.x, view.center.y-2)];
                    NSValue * p3 = [NSValue valueWithCGPoint:CGPointMake(view.center.x, view.center.y-4)];
                    NSValue * p4 = [NSValue valueWithCGPoint:CGPointMake(view.center.x, view.center.y-2)];
                    NSValue * p5 = [NSValue valueWithCGPoint:CGPointMake(view.center.x, view.center.y)];
                    keyAnimation.duration = 1.5;
                    keyAnimation.repeatCount = MAXFLOAT;
                    keyAnimation.values = @[p1,p2,p3,p4,p5];
                    
                    CABasicAnimation * opacityAnimation =[CABasicAnimation animationWithKeyPath:@"opacity"];
                    opacityAnimation.fromValue= [NSNumber numberWithInt:1];
                    opacityAnimation.toValue= [NSNumber numberWithInt:0];
                    opacityAnimation.duration = 3;
                    opacityAnimation.repeatCount = MAXFLOAT;
                    
                    CAAnimationGroup *groupAnnimation = [CAAnimationGroup animation];
                    groupAnnimation.duration =1.5;
                    groupAnnimation.autoreverses = YES;
                    groupAnnimation.animations = @[keyAnimation,opacityAnimation];
                    groupAnnimation.repeatCount = MAXFLOAT;
                    
                    [view.layer addAnimation:groupAnnimation forKey:@"keyAnimation"];
                    
                }
            }else{
                [view.layer removeAllAnimations];
                view.hidden = YES;

            }
        }
    }
}

-(void) preProcessImageFor2X:(ImageLoadingOptions*) options
{
#if ALLOW_2X_STYLE_SCALING_OF_SVGS_AS_AN_EXAMPLE
    if( [options.localFileSource.filePath hasSuffix:@"@2x"])
    {
        SVGKSourceLocalFile* modifiedSource = [options.localFileSource copy];
        modifiedSource.filePath = [modifiedSource.filePath substringToIndex:modifiedSource.filePath.length - @"@2x".length];
        options.overrideImageRenderScale = 2.0;
        options.requiresLayeredImageView = true;
        options.localFileSource = modifiedSource;
    }
#endif
}

/**
 If you want to emulate Apple's @WxH naming system for UIImage, you can...
 */
-(void) preProcessImageForAt160x240:(ImageLoadingOptions*) options
{
    if( [options.localFileSource.filePath hasSuffix:@"@160x240"]) // could be any 999x999 you want, up to you to implement!
    {
        SVGKSourceLocalFile* modifiedSource = [options.localFileSource copy];
        
        modifiedSource.filePath = [modifiedSource.filePath substringToIndex:modifiedSource.filePath.length - @"@160x240".length];
        options.overrideImageSize = CGSizeMake( 160, 240 );
        
        options.localFileSource = modifiedSource;
    }
}


-(void) preProcessImageCheckWorkaroundAppleBugInGradientImages:(ImageLoadingOptions*) options rangeString:(NSString*)rangeString
{
    if([options.localFileSource.filePath rangeOfString:rangeString].location != NSNotFound // Monkey uses layer-animations, so REQUIRES the layered version of SVGKImageView
       ){
        /**
         
         NB: special-case handling here -- this is included AS AN EXAMPLE so you can see the differences.
         
         MONKEY.SVG -- CAAnimation of layers
         -----
         The problem: Apple's code doesn't allow us to support CoreAnimation *and* make image loading easy.
         The solution: there are two versions of SVGKImageView - a "normal" one, and a "weaker one that supports CoreAnimation"
         
         In this demo, we setup the Monkey.SVG to allow layer-based animation...
         
         
         RAINBOWWING.SVG -- Gradient-fills of shapes
         -----
         The problem: Apple's renderInContext has a major bug where it ignores CALayer masks
         The solution: there are two versions of SVGKImageView - a "normal" one, and a "weaker one that doesnt use renderInContext"
         
         */
        options.requiresLayeredImageView = true;
    }
}





#pragma mark -=================== draw
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    if (pathArray != nil) {
        [pathArray removeAllObjects];
    }
    CGContextRef context = UIGraphicsGetCurrentContext();
    //抗锯齿
    CGContextSetAllowsAntialiasing(context, TRUE);
    CGContextSetShouldAntialias(context, true);
    
    int i = 0;
    
    for (id obj in _pointsArray) {
        
        if ([obj isKindOfClass:[PrimitivePoints class]])//商铺
        {
            PrimitivePoints *point = obj;
            
            if ([point.type isEqualToString:@"PLINE"])
            {
                //读取点集合
                NSMutableArray *regionPoints = point.pointArray;
                for (int i = 0; i < regionPoints.count; i++) {
                    MPoint *point = [regionPoints objectAtIndex:i];
                    
                    if (i == 0)
                    {
                        CGContextMoveToPoint(context, (point.x  - OFFSET_X) * RATIO, (MAP_HEIGHT - point.y) * RATIO + _offset_y);  // 开始坐标右边开始
                        continue;
                    }
                    
                    CGContextAddLineToPoint(context, (point.x - OFFSET_X) * RATIO, (MAP_HEIGHT - point.y) * RATIO + _offset_y);
                }
                
                //区分不同情况
                if (point.hasProperty)
                {
                    
                    if ([point.property.propertyNo intValue] == 20)//车位
                    {
                        //构建区域，用于点击操作
                        IndoorMapPath *mapPath = [[IndoorMapPath alloc] initWithPrimitives:regionPoints areaLocation:@""];
                        
                        //区域path, 同时也是障碍物path
                        [pathArray addObject:mapPath];
                        
                        CGContextSetLineWidth(context, 0.0f);
                        if (sIndex == i)
                        {
                            CGContextSetFillColorWithColor(context, COLOR_MAP_MAIN.CGColor);
                        }
                        else
                        {
                            CGContextSetFillColorWithColor(context, COLOR_MAP_PARKING.CGColor);
                        }
                        
                        CGContextClosePath(context);
                        CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径
                        i++;
                    }
                    else if ([point.property.propertyNo intValue] == 22)//建筑
                    {
                        [pathArray addObject:[NSNull null]];
                        CGContextSetLineWidth(context, 0.0f);
                        //                        CGContextSetStrokeColorWithColor(context, COLOR_MAP_FRAME.CGColor);//线框颜色
                        CGContextSetFillColorWithColor(context, COLOR_MAP_BUILDING.CGColor);
                        CGContextClosePath(context);
                        CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径
                    }
                    else if ([point.property.propertyNo intValue] == 40)//外框
                    {
                        [pathArray addObject:[NSNull null]];
                        CGContextSetLineWidth(context, 10.0f);
                        CGContextSetStrokeColorWithColor(context, COLOR_MAP_FRAME.CGColor);//线框颜色
                        CGContextClosePath(context);
                        CGContextDrawPath(context, kCGPathStroke); //根据坐标绘制路径
                    }
                    else
                    {
                        //构建区域，用于点击操作
                        IndoorMapPath *mapPath = [[IndoorMapPath alloc] initWithPrimitives:regionPoints areaLocation:@""];
                        
                        //区域path, 同时也是障碍物path
                        [pathArray addObject:mapPath];
                        
                        CGContextSetLineWidth(context, 0.0f);
                        CGContextSetFillColorWithColor(context, COLOR_MAP_BUILDING.CGColor);
                        CGContextClosePath(context);
                        CGContextDrawPath(context, kCGPathFillStroke);
                        i++;
                    }
                    
                }
                else
                {
                    //构建区域，用于点击操作
                    IndoorMapPath *mapPath = [[IndoorMapPath alloc] initWithPrimitives:regionPoints areaLocation:@""];
                    
                    //区域path, 同时也是障碍物path
                    [pathArray addObject:mapPath];
                    
                    CGContextSetLineWidth(context, 0.0f);
                    if (sIndex == i) {
                        CGContextSetFillColorWithColor(context, COLOR_MAP_FASHION.CGColor);
                    }else{
                        CGContextSetFillColorWithColor(context, COLOR_MAP_MAIN.CGColor);
                    }
                    //            CGContextSetStrokeColorWithColor(context, [UIColor yellowColor].CGColor);//线框颜色
                    CGContextClosePath(context);
                    CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径
                    i++;
                }
                
            }
        }
        else if ([obj isKindOfClass:[FacilityPoints class]])//设施图标
        {
//            return;
//            if (isFindingcar) {
//                continue;
//            }
//            if (isSameFloor) {
//                continue;
//            }
        }
        
    }
    
}

#pragma mark - UITouch 描边框==========
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UIView * view in self.subviews) {
        if (view.tag>=1000 &&view.tag<10000 &&[view.layer animationForKey:@"keyAnimation"]) {
            [view.layer removeAllAnimations];
        }
    }
    // cancel previous touch ended event
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    
	CGPoint touchPoint  = [[touches anyObject] locationInView:self];
    NSValue *touchValue = [NSValue valueWithCGPoint:touchPoint];
    
    // perform new one
//    [self performSelector:@selector(performTouchTestArea:)
//               withObject:touchValue
//               afterDelay:0.1];
    [self performSelector:@selector(performTouchTestArea2:)
               withObject:touchValue
               afterDelay:0.1];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"touch_ended" object:nil];
    
    
    ////画框框
    CGPoint p =touchPoint;
    
#if ALLOW_SVGKFASTIMAGEVIEW_TO_DO_HIT_TESTING // look how much code this requires! It's insane! Use SVGKLayeredImageView instead if you need hit-testing!
    SVGKImage* svgImage = nil; // ONLY used for the hacky code below that demonstrates how complex hit-testing is on an SVGKFastImageView
    
    /**
     WARNING:
     
     Whenever you're using SVGKFastImageView, it "hides" the raw CALayers from you, and Apple
     doesn't provide an easy way around this (we do it this way because there are missing methods
     and bugs in Apple's UIScrollView, which SVGKFastImageView fixes).
     
     So, you cannot do a hittest on "SVGKFastImageView.layer" - that will always return the root,
     empty, full-size layer.
     
     Instead, you have to hit-test the layer INSIDE the fast imageview.
     
     --------
     
     HOWEVER: YOU SHOULD NOT BE DOING THIS!
     
     IF YOU NEED TO DO HIT-TESTING, USE SVGKLayeredImageView (as per the docs!)
     
     THE EXAMPLE CODE HERE SHOWS YOU HOW YOU COULD, IN THEORY, DO HIT-TESTING WITH EITHER, BUT IT
     IS HIGHLY RECOMMENDED NEVER TO USE HIT-TESTING WITH SVGKFastImageView!
     */
#endif
    CALayer* layerForHitTesting;
    
#if ALLOW_SVGKFASTIMAGEVIEW_TO_DO_HIT_TESTING // look how much code this requires! It's insane! Use SVGKLayeredImageView instead if you need hit-testing!
    if( [self.contentView isKindOfClass:[SVGKFastImageView class]])
    {
        layerForHitTesting = ((SVGKFastImageView*)self.contentView).image.CALayerTree;
        svgImage = ((SVGKFastImageView*)self.contentView).image;
        
        /**
         ALSO, because SVGKFastImageView DOES NOT ALTER the underlying layers when it zooms
         (the zoom is handled "fast" and done internally at 100% accuracy),
         any zoom will be ignored for the hit-test - we have to MANUALLY apply the zoom
         */
        CGSize scaleConvertImageToViewForHitTest = CGSizeMake( self.contentView.bounds.size.width / svgImage.size.width, self.contentView.bounds.size.height / svgImage.size.height ); // this is a copy/paste of the internal "SCALING" logic used in SVGKFastImageView
        
        p = CGPointApplyAffineTransform( p, CGAffineTransformInvert( CGAffineTransformMakeScale( scaleConvertImageToViewForHitTest.width, scaleConvertImageToViewForHitTest.height)) ); // must do the OPPOSITE of the zoom (to convert the 'seeming' point to the 'actual' point
    }
    else
#endif
        layerForHitTesting = self.contentView.layer;
    
    
    CALayer* hitLayer = [layerForHitTesting hitTest:p];
    
    if( hitLayer == lastTappedLayer )
        [self deselectTappedLayer]; // do this both ways, but have to do it AFTER the if-test because it nil's one of the if-phrases!
    else {
        [self deselectTappedLayer]; // do this both ways, but have to do it AFTER the if-test because it nil's one of the if-phrases!
        
#if ALLOW_SVGKFASTIMAGEVIEW_TO_DO_HIT_TESTING // look how much code this requires! It's insane! Use SVGKLayeredImageView instead if you need hit-testing!
        //        self.title = @"";
        // reset it so that we can conditionally set it - but also ensuring this code is included in the #if
        if( [self.contentView isKindOfClass:[SVGKFastImageView class]])
        {
            /** NEVER DO THIS - this is a proof-of-concept, but instead you should ALWAYS
             use SVGKLayeredImageView if you want to do hit-testing!
             */
            //            self.title = @"WARNING: don't use SVGKFastImageView for hit-testing";
            
            /**
             Because SVGKFastImageView "hides" the layers, any visual changes we make
             will NOT be reflected on-screen.
             
             Instead, we have to put a NEW layer over the top
             */
            CALayer* absolutePositionedCloneLayer = [svgImage newCopyPositionedAbsoluteOfLayer:hitLayer];
            
            lastTappedLayer = [[CALayer alloc] init];
            lastTappedLayer.frame = absolutePositionedCloneLayer.frame;
            
            /**
             ALSO, because SVGKFastImageView DOES NOT ALTER the underlying layers when it zooms
             (the zoom is handled "fast" and done internally at 100% accuracy),
             any zoom will be ignored for the new layer - we have to MANUALLY apply the zoom
             */
            CGSize scaleConvertImageToView = CGSizeMake( self.contentView.bounds.size.width / svgImage.size.width, self.contentView.bounds.size.height / svgImage.size.height ); // this is a copy/paste of the internal "SCALING" logic used in SVGKFastImageView
//            lastTappedLayer.frame = CGRectApplyAffineTransform( lastTappedLayer.frame, CGAffineTransformMakeScale(scaleConvertImageToView.width, scaleConvertImageToView.height));
#pragma mark ======= 注释边框
//            [self.contentView.layer addSublayer:lastTappedLayer];
        }
        else
#endif
            lastTappedLayer = hitLayer;
        
        if( lastTappedLayer != nil )
        {
//            lastTappedLayerOriginalBorderColor = lastTappedLayer.borderColor;
//            lastTappedLayerOriginalBorderWidth = lastTappedLayer.borderWidth;
//            
//            lastTappedLayer.borderColor = [UIColor greenColor].CGColor;
//            lastTappedLayer.borderWidth = 3.0;
            
        }
    }

    
}
- (void)performTouchTestArea2:(NSValue *)inTouchPoint
{
    CGPoint aTouchPoint = [inTouchPoint CGPointValue];
//    self.userImage.frame = CGRectMake(aTouchPoint.x-9, aTouchPoint.y-9, 18, 18);
//    CGPoint ponit = CGPointMake(aTouchPoint.x*458/320, (aTouchPoint.y-90)*404/280);
//    CGPoint ponit = CGPointMake(aTouchPoint.x*1325/320, (aTouchPoint.y-90-44)*819/(280));
    CGPoint ponit = CGPointMake(aTouchPoint.x, aTouchPoint.y);
    NSLog(@"-----------%@",NSStringFromCGPoint(ponit));
    [_delegate touchPosition:ponit];

}
- (void)performTouchTestArea:(NSValue *)inTouchPoint
{
    CGPoint aTouchPoint = [inTouchPoint CGPointValue];
    
    BOOL isInArea = NO;
    if (pathArray != nil) {
        int i = 0;
        for (id obj in pathArray) {
            IndoorMapPath *path = obj;
            if (![obj isEqual:[NSNull null]] && [path isAreaSelected:aTouchPoint]) {
                sIndex = i;
                [self setNeedsDisplay];
                
                PrimitivePoints *content = [_pointsArray objectAtIndex:i];
                [_delegate touchPosition:CGPointMake(aTouchPoint.x, aTouchPoint.y) content:content];
                isInArea = YES;
            }
            i++;
        }
        
        if (!isInArea) {
//            [_delegate touchPosition:CGPointMake(0, 0) content:nil];
            [_delegate touchPosition:CGPointMake(0, 0) content:nil];
        }
    }
}

#pragma mark - get path Point
/**
 *  获取路径点集合
 */
- (NSMutableArray *)fetchPathPoint:(NSString *)filePath
{
    NSMutableArray *results = [[NSMutableArray alloc] init];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"map1_path_data" ofType:@"txt"];
    
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    
    NSData *lineData;
    
    while ((lineData = [fileHandle readLineWithDelimiter:@"\n"]))
    {
        NSString *lineString = [[NSString alloc] initWithData:lineData encoding:NSUTF8StringEncoding];
        
        //#号为注释
        if ([lineString characterAtIndex:0] == '#')
        {
            continue;
        }
        NSString *replaceStr = [lineString stringByReplacingOccurrencesOfString:@"(" withString:@"{"];
        NSString *replaceStr1 = [replaceStr stringByReplacingOccurrencesOfString:@")" withString:@"}"];
        
        //转换坐标系，跟障碍物区域
        CGPoint point = CGPointFromString(replaceStr1);
        point.x = point.x;
        point.y = (760 - point.y);
        
        point.x = (point.x / 100.0f  - OFFSET_X) * RATIO;
        point.y = (MAP_HEIGHT - point.y / 100.0f) * RATIO + _offset_y;
        
        AStarItem *item = [[AStarItem alloc] init];
        [item setPos:point.x row:point.y];
        [results addObject:item];
    }
    return results;
}

#pragma mark ======= 查找商城设施点集合
- (NSMutableArray *)fetchFacilityPoint:(NSString *)filePath
{
    NSMutableArray *results = [[NSMutableArray alloc] init];
    NSString *path = [[NSBundle mainBundle] pathForResource:filePath ofType:@"txt"];
    
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    
    NSData *lineData;
    
    while ((lineData = [fileHandle readLineWithDelimiter:@"\n"]))
    {
        NSString *lineString = [[NSString alloc] initWithData:lineData encoding:NSUTF8StringEncoding];
        
        //#号为注释
        if ([lineString characterAtIndex:0] == '#')
        {
            continue;
        }
        NSString *replaceStr = [lineString stringByReplacingOccurrencesOfString:@"(" withString:@"{"];
        NSString *replaceStr1 = [replaceStr stringByReplacingOccurrencesOfString:@")" withString:@"}"];
        
        NSArray *array = [replaceStr1 componentsSeparatedByString:@"||"];
        for (int j = 0; j<array.count; j++) {
            NSString * replaceStr = array[j];
            NSArray * Array = [replaceStr componentsSeparatedByString:@";"];
            NSMutableArray *points = [[NSMutableArray alloc] init];
            if (Array) {
                
                for (int i = 0; i < Array.count; i++) {
                    
                    NSString *pointStr = [Array objectAtIndex:i];
                    pointStr = [pointStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                    pointStr = [pointStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    
                    if (![points containsObject:pointStr])
                    {
                        [points addObject:pointStr];
                    }
                    
                }
            }
            
            NSMutableArray * arr = [NSMutableArray array];
            for (NSString *pointStr in points) {
                
                AStarItem *item = [[AStarItem alloc] init];
                
                CGPoint point = CGPointFromString(pointStr);
                
                //转换坐标系
                //        point.y = 760 - point.y;
                //
                //        point.x = (point.x / 100.0f  - OFFSET_X) * RATIO;
                //        point.y = (MAP_HEIGHT - point.y / 100.0f) * RATIO + _offset_y;
                
                [item setPos:point.x row:point.y];
                
                //结点集合
                [arr addObject:item];
            }
            [results addObject:arr];
        }
    }
    
       return results;
}

/**
 *  获取线段集合
 *
 *  @param filePath 路径
 *
 *  @return 线段集合
 */
- (NSMutableArray *)fetchPathPairPoint:(NSString *)filePath
{
    NSMutableArray *results = [[NSMutableArray alloc] init];
    NSString *path = [[NSBundle mainBundle] pathForResource:filePath ofType:@"txt"];
    
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    
    NSData *lineData;
    
    NSMutableArray *points = [[NSMutableArray alloc] init];
    while ((lineData = [fileHandle readLineWithDelimiter:@"\n"]))
    {
        NSString *lineString = [[NSString alloc] initWithData:lineData encoding:NSUTF8StringEncoding];
        
        //#号为注释
        if ([lineString characterAtIndex:0] == '#')
        {
            continue;
        }
        NSString *replaceStr = [lineString stringByReplacingOccurrencesOfString:@"(" withString:@"{"];
        NSString *replaceStr1 = [replaceStr stringByReplacingOccurrencesOfString:@")" withString:@"}"];
        
        NSArray *array = [replaceStr1 componentsSeparatedByString:@"-"];
        if (array) {
            
            ItemRelation *relation = [[ItemRelation alloc] init];
            
            for (int i = 0; i < array.count; i++) {
                
                NSString *pointStr = [array objectAtIndex:i];
                pointStr = [pointStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                pointStr = [pointStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                
                if (![points containsObject:pointStr])
                {
                    [points addObject:pointStr];
                }
                
                CGPoint point = CGPointFromString(pointStr);
                
                //转换坐标系
//                point.y = 760 - point.y;
//                
//                point.x = (point.x / 100.0f  - OFFSET_X) * RATIO;
//                point.y = (MAP_HEIGHT - point.y / 100.0f) * RATIO + _offset_y;
                
                if (i == 0)
                {
                    relation.point1.col = point.x;
                    relation.point1.row = point.y;
                }
                else
                {
                    relation.point2.col = point.x;
                    relation.point2.row = point.y;
                }
                
                
            }
            //关系点集合
            [astar.relationArray addObject:relation];
        }
        
    }
    
    for (NSString *pointStr in points) {
        
        AStarItem *item = [[AStarItem alloc] init];
        
        
        CGPoint point = CGPointFromString(pointStr);
        
        //转换坐标系
//        point.y = 760 - point.y;
//        
//        point.x = (point.x / 100.0f  - OFFSET_X) * RATIO;
//        point.y = (MAP_HEIGHT - point.y / 100.0f) * RATIO + _offset_y;
        
        [item setPos:point.x row:point.y];
        
        //结点集合
        [results addObject:item];
    }
    return results;
}

/**
 *  画商场地图路径
 */
- (NSMutableArray *)findPathStartX:(CGFloat)startX
                             statY:(CGFloat)startY
                              endX:(CGFloat)endX
                              endY:(CGFloat)endY
                          filePath:(NSString *)filePath
{

    NSMutableArray *points = [self fetchPathPairPoint:filePath];
    astar.allPointsArray = [points mutableCopy];
    
    NSMutableArray *pathsArray = [[NSMutableArray alloc] init];
    
    //转换成与路径点相同的坐标系
    CGFloat x_start = startX;
    CGFloat y_start = startY;
    CGFloat x_end = endX;
    CGFloat y_end = endY;
    
    //图片大小458*404
    //转化成可绘制坐标
//    CGFloat x_ratio = 320 / 458.0f;
//    CGFloat y_ratio = self.contentView.frame.size.height / 404.f;
//    x_start = x_start * x_ratio;
//    y_start = y_start * y_ratio;// + _offset_y;
//    x_end = x_end * x_ratio;
//    y_end = y_end * y_ratio;// + _offset_y;
    
//    NSLog(@"start----->(%f, %f)", x_start, y_start);
    
    AStarItem *item_start_nearest = [astar findNearestPoint:x_start row:y_start];
    
    AStarItem *item_end_nearest = [astar findNearestPoint:x_end row:y_end];

    newPath = [astar findPath:item_start_nearest.id_col
                         curY:item_start_nearest.id_row
                         aimX:item_end_nearest.id_col
                         aimY:item_end_nearest.id_row
                     withPath:nil];
    
    //添加起点，终点两头
    AStarItem *itemStart = [[AStarItem alloc] init];
    itemStart.id_col = x_start;
    itemStart.id_row = y_start;
    
    AStarItem *itemEnd = [[AStarItem alloc] init];
    itemEnd.id_col = x_end;
    itemEnd.id_row = y_end;
    [newPath insertObject:itemStart atIndex:0];
    [newPath addObject:itemEnd];
    
    pathsArray = [newPath mutableCopy];
    
    NSMutableArray * xArray = [NSMutableArray array];
    NSMutableArray * yArray = [NSMutableArray array];
    for (AStarItem * item in pathsArray) {
        int x = item.id_col;
        int y = item.id_row;
        [xArray addObject:@(x)];
        [yArray addObject:@(y)];
    }
//    [pathsArray removeLastObject];
    return pathsArray;
    
}

- (void)drawPaths:(NSMutableArray *)path
{
    //绘制路线
    [pathView drawPathWithPoints:path];
   
}

- (void)cleanPath{
    [pathView drawPathWithPoints:nil];
}

@end
